<?php declare(strict_types=1);

namespace App\Process;

use Hyperf\Process\AbstractProcess;
use Hyperf\Redis\Redis;
use Hyperf\Redis\RedisFactory;
use Psr\Container\ContainerInterface;

class RedisExpireListener extends AbstractProcess
{

    public int $nums = 1;

    public string $name = 'redis-expire-listener';

    public bool $enableCoroutine = true;

    protected Redis $redis;

    public function __construct(ContainerInterface $container)
    {
        parent::__construct($container);
        $this->redis = $container->get(RedisFactory::class)->get('process');
    }


    public function handle(): void
    {
        /**
         * 订阅 key 的过期信息
         * @remark 此功能正常使用需要 redis 配置文件设置配置项 “notify-keyspace-events Ex”
         * @descrebe __keyevent@[*|DbIdx]__:expired *监听所有db，指定 DbIdx 则只监听对应的数据库
         */
        $that = $this;
        // 获取当前redis数据库的下标
        $redisDbIdx = $this->redis->getDbNum();
        $this->redis->psubscribe(["__keyevent@{$redisDbIdx}__:expired"], function ($redis, $pattern, $chan, $msg) use ($that) {
            stdPrinter()->warning('RedisKey: "' . $msg . '" is expired ! ' . date('Y-m-d H:i:s'));
            $that->keyExpireHandler($msg);
        });
    }

    /**
     * 对过期的key 进行业务匹配，若需要特殊处理就进行相应的处理
     * @param string $key
     * @return void
     */
    protected function keyExpireHandler(string $key): void
    {

    }
}